package xin.nick.exception;


import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;
import xin.nick.entity.Result;

import java.util.List;

/**
 * 全局异常拦截
 * @author Nick
 * @since 2022/7/21/021
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {



    private MessageSource messageSource;

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Result<String> handleNoHandlerFoundException(NoHandlerFoundException e) {
        return Result.custom(HttpStatus.NOT_FOUND.value(), "页面不存在");
    }



    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return Result.paramError("请求方式不支持");
    }

    /**
     * 参数类型异常
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.warn("参数类型异常: {}", e.getMessage());
        return Result.paramError("参数类型异常");
    }

    /**
     * 参数异常信息
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<String> handleIllegalArgumentException(IllegalArgumentException e) {
        String msg =  e.getMessage();
        log.warn("参数异常: {}", msg);
        return Result.paramError(msg);
    }

    /**
     * 参数类型缺失
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<String> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.warn("参数类型缺失: {}", e.getMessage());
        return Result.paramError("参数类型缺失");
    }

    /**
     * 请求的媒体类型不支持
     */
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<String> handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
        log.warn("请求的媒体类型不支持: {}", e.getMessage());
        return Result.paramError("请求的媒体类型不支持");
    }

    /**
     * MultipartException
     */
    @ExceptionHandler(MultipartException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<String> handleMultipartException(MultipartException e) {
        log.warn("多参数上传出错: {}", e.getMessage());
        return Result.paramError("多参数上传出错");
    }

    /**
     * MissingServletRequestPartException
     */
    @ExceptionHandler(MissingServletRequestPartException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<String> handleMissingServletRequestPartException(MissingServletRequestPartException e) {
        log.warn("参数缺失: {}", e.getMessage());
        return Result.paramError("参数缺失");
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> validExceptionHandler(MethodArgumentNotValidException e) {
        StringBuilder errorMessage = new StringBuilder();
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> errors = bindingResult.getFieldErrors();
        errors.forEach(error ->
                errorMessage.append(error.getDefaultMessage()).append(";")
        );
        return Result.paramError(errorMessage.toString());
    }

    /**
     * 自定义业务异常
     * @param e 异常
     * @return 返回规范的异常信息
     */
    @ExceptionHandler(CustomException.class)
    public Result<String> handleMyException(CustomException e) {
        String message = e.getMessage();
        Integer code = e.getCode();
        log.warn("自定义业务异常: {}", message);
        return Result.custom(code, message);
    }


    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> handleException(Exception e) {
        log.error("Exception", e);
        return Result.error();
    }


    // FileSizeLimitExceededException
    @ExceptionHandler(FileSizeLimitExceededException.class)
    public Result<String> handleFileSizeLimitExceededException(FileSizeLimitExceededException e) {
        return Result.paramError( "文件过大");
    }

}
